package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //正常用户
        if(StringUtils.isNotBlank(loginDto.getPhone())&&StringUtils.isNotBlank(loginDto.getPassword())){
          //查询app_user,密码校验
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser apUser = this.getOne(queryWrapper);
            if(apUser!=null){
                //密码校验
                String dbPassword = apUser.getPassword(); //数据库加后的密密码
                String loginDtoPassword = loginDto.getPassword(); //明文
               //明文从新加盐
                String md5DigestAsHex = DigestUtils.md5DigestAsHex((loginDtoPassword + apUser.getSalt()).getBytes());
                //数据库比对
                if(md5DigestAsHex.equals(dbPassword)){
                    HashMap<Object, Object> data = new HashMap<>();
                    data.put("data",apUser);
                    apUser.setSalt("");
                    apUser.setPassword("");
                    data.put("token", AppJwtUtil.getToken(Long.valueOf(apUser.getId())));
                    return  ResponseResult.okResult(data);
                }else{
                    return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else{
                return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }


        }else{
            HashMap<Object, Object> data = new HashMap<>();
            data.put("token", AppJwtUtil.getToken(0L));
            return  ResponseResult.okResult(data);
        }

    }
}
